package com.weifly.weistock.record.data.impl;

import com.weifly.weistock.record.data.DataHistoryService;
import com.weifly.weistock.record.data.DataStoreService;
import com.weifly.weistock.record.data.domain.StockDayDto;
import com.weifly.weistock.record.data.domain.StockDataDto;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 市场数据服务实现
 *
 * @author weifly
 * @since 2019/9/29
 */
public class DataHistoryServiceImpl implements DataHistoryService {

    private SortedMap<String, StockDataDto> stockMap = new TreeMap<>(); // key有序的map

    private DataStoreService dataStoreService;

    public void setDataStoreService(DataStoreService dataStoreService) {
        this.dataStoreService = dataStoreService;
    }

    @Override
    public void updateStockList(List<StockDataDto> stockList) {
        this.stockMap.clear();
        for(StockDataDto stockDto : stockList){
            this.stockMap.put(stockDto.getCode(), stockDto);
        }
    }

    @Override
    public void updateStockData(StockDataDto stockDto) {
        if(stockDto!=null){
            this.stockMap.put(stockDto.getCode(), stockDto);
            this.dataStoreService.saveStockData(stockDto);
        }
    }

    @Override
    public List<StockDayDto> loadChartDayList(String stockCode, String lowDay) {
        LinkedList<StockDayDto> dayList = new LinkedList<>();
        if(StringUtils.isBlank(lowDay)){
            return dayList;
        }
        StockDataDto stockDto = this.stockMap.get(stockCode);
        if(stockDto==null || stockDto.getDayList()==null){
            return dayList;
        }

        Iterator<StockDayDto> dayIter = stockDto.getDayList().iterator();
        while(dayIter.hasNext()){
            StockDayDto dayDto = dayIter.next();
            if(lowDay.compareTo(dayDto.getDay())<=0){
                dayList.add(dayDto);
            }
        }
        return dayList;
    }
}
